﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Commen;
using Code.BLL;
using Code.Models;
using System.Configuration;

namespace Code.BLL
{
    public class IssueManage : ManageBase<Issue>
    {
        public int EditIssue(Issue issue)
        {
            int rs = -1;


            return rs;
        }

        /// <summary>
        /// 删除指定的期号
        /// </summary>
        /// <param name="ids">期号ID</param>
        /// <returns></returns>
        public int DeleteIssue(params long[] ids)
        {
            int rs = -1;
            if (ids.Length > 100)
            {
                rs = 0;
                int count = (int)Math.Ceiling(ids.Length / 100.0);
                for (int i = 0; i < count; i++)
                {
                    var temp = new { ID = new ComparValue(Comparison.In, ids.Skip(i * 100).Take(100)) };
                    rs += base.Delete(temp);
                }
            }
            else
            {
                var del = new { ID = new ComparValue(Comparison.In, ids) };
                rs = base.Delete(del);
            }
            return rs;
        }

        /// <summary>
        /// 删除指定时间内的期号，以期号的结束时间判断
        /// </summary>
        /// <param name="start">起始时间，如果要删除指定时间之前的期号，此处为 NULL</param>
        /// <param name="end">结束时间</param>
        /// <returns></returns>
        public int DeleteIssue(int? lottery, DateTime? start, DateTime end)
        {
            int rs = -1;
            var del = new NameValue<string, object>();
            var item = new NameValueItem<string, object>();
            item.Key = "EndTime";
            if (start.HasValue)
                item.Value = new ComparValue(Comparison.Between, start.Value, end.AddDays(1));
            else
                item.Value = new ComparValue(Comparison.LessThanOrEqual, end.AddDays(1));
            del.Add(item);
            if (lottery.HasValue)
                del.Add("LotteryID", lottery.Value);
            del.Add("NULL", new SqlExpression("not exists (select 1 from Scheme where Issue.ID=IssueID) and not exists(select 1 from ChaseTask_Detail where Issue.ID=IssueID)"));
            rs = base.Delete(del);
            return rs;
        }

        /// <summary>
        /// 增加期号
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        /// <param name="starttime">开始日期，只取日期瓿份</param>
        /// <param name="date">增加的天数</param>
        /// <returns>增加了多少期 -1 为数据库操作失败</returns>
        public int AddIssue(LotteryType lotteryid, DateTime starttime, int date)
        {
            IList<Issue> issues = BuildIssue(lotteryid, starttime, date);
            if (issues != null && issues.Count() > 0)
            {
                var tmp1 = issues.Select(p => new { p.Number, p.LotteryID, p.StartTime, p.EndTime });
                var firsttime = tmp1.OrderBy(pp => pp.StartTime).First().StartTime;
                var lasttime = tmp1.OrderByDescending(p => p.StartTime).First().StartTime;

                var tmp2 = base.Select(s=>s.Where(p => p.LotteryID == (int)lotteryid && p.StartTime >= firsttime && p.StartTime <= lasttime).Select(p => p.Number)).ToArray();
                var ups = tmp1.Where(p => !(tmp2.Contains(p.Number))).ToArray();
                if (ups.Length > 0)
                {

                    return base.Insert(ups);
                }
            }
            return 0;
        }

        /// <summary>
        /// 或取当前彩种所有期号
        /// </summary>
        /// <param name="lotteryid"></param>
        /// <returns></returns>
        public Issue[] GetAllIssue(LotteryType lotteryid)
        {
            return Tables.Issue.Where(p => p.LotteryID == (int)lotteryid).ToArray();
        }
        /// <summary>
        /// 根据ID获取期号
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        /// <param name="issueid">ID号</param>
        public Issue GetIssueByID(LotteryType lotteryid, long issueid)
        {
            Issue rs;
            rs = Tables.Issue
                .Where(p => p.ID == issueid && p.LotteryID == (int)lotteryid).FirstOrDefault();
            return rs;
        }
        /// <summary>
        /// 跟据期号查询期号信息
        /// </summary>
        /// <param name="issuename">期号</param>
        /// <param name="lottery">彩种</param>
        public Issue GetIssue(string issuename, LotteryType lottery)
        {
            Issue rs = null;
            issuename = Issue.BulidIssueName(lottery, issuename);
            rs = Tables.Issue.FirstOrDefault(p => p.Number == issuename && p.LotteryID == (int)lottery);
            return rs;
        }
        /// <summary>
        /// 根据搜索条件获取期号列表
        /// </summary>
        /// <param name="search">搜索条件</param>
        /// <param name="skip">用户于分页查询时要跳过的条数</param>
        /// <param name="take">用户于分页查询时要查询的条数</param>
        /// <param name="sumCount">在分页之前的总条数</param>
        /// <returns></returns>
        public IEnumerable<Issue> GetIssueList(SearchIssue_Mod search, int skip, int take, out int sumCount)
        {
            var data = base.Select(s => s);
            if (search != null)
            {
                if (search.LotteryID.HasValue)
                    data = data.Where(p => p.LotteryID == search.LotteryID.Value);
                if (search.StartTime.HasValue)
                    data = data.Where(p => p.StartTime >= search.StartTime.Value);
                if (search.EndTime.HasValue)
                    data = data.Where(p => p.EndTime < search.EndTime.Value.AddDays(1));
                if (search.State.HasValue)
                    data = data.Where(p => p.State == search.State.Value);
                if (!string.IsNullOrEmpty(search.FomartNumber)&&search.LotteryID.HasValue)
                    data = data.Where(p => p.Number == Issue.BulidIssueName((LotteryType)search.LotteryID.Value, search.FomartNumber));
            }
            sumCount = data.Count();
            return data.OrderBy(p=>p.StartTime).Skip(skip).Take(take);
        }

        /// <summary>
        /// 获取当前期的上一期
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        public Issue GetPriorIssue(LotteryType lotteryid)
        {
            Issue rs = null;

            rs = Tables.Issue
                .Where(p => p.EndTime < DateTime.Now && p.LotteryID == (int)lotteryid)
                .OrderByDescending(p => p.StartTime)
                .FirstOrDefault();
            return rs;
        }

        /// <summary>
        /// 获取当前期
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        public Issue GetCurrentIssue(LotteryType lotteryid)
        {
            Issue rs;
            rs = Tables.Issue
                .Where(p => p.EndTime > DateTime.Now && p.StartTime < DateTime.Now && p.LotteryID == (int)lotteryid)
                .OrderByDescending(p => p.StartTime).FirstOrDefault();
            return rs;
        }

        /// <summary>
        /// 获取当前期的下一期(已格式化)
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        public Issue GetNextIssue(LotteryType lotteryid)
        {
            Issue rs = Tables.Issue.Where(p => p.LotteryID == (int)lotteryid && p.StartTime >= DateTime.Now).OrderBy(p => p.StartTime).FirstOrDefault();
            return rs;
        }

        /// <summary>
        /// 获取下一期
        /// </summary>
        /// <param name="lotteryid">彩种</param>
        /// <param name="currentStart">当前期的开始时间</param>
        /// <returns>下一期的信息</returns>
        public Issue GetNextIssue(LotteryType lotteryid, DateTime currentStart)
        {
            Issue rs = null;
            rs = Tables.Issue.OrderBy(p => p.StartTime).FirstOrDefault(p => p.StartTime > currentStart && p.LotteryID == (int)lotteryid);
            return rs;
        }


        /// <summary>
        /// 生成期号
        /// </summary>
        /// <param name="lottery">彩种</param>
        /// <param name="start">开始日期，只要日期部份</param>
        /// <param name="date">生成多少天的期号</param>
        public IList<Issue> BuildIssue(LotteryType lottery, DateTime start, int date)
        {
            // 数字排列 和 福彩3D
            if (lottery == LotteryType.SZPL || lottery == LotteryType.FC3D || lottery == LotteryType.HaoCai1)
                return BuildIssueByDay(lottery, start, date);

            if (char.IsNumber(lottery.ToString()[0]))
                throw new ArgumentOutOfRangeException("lottery", lottery.ToString());

            IList<Issue> rs = new List<Issue>();

            string[] tmp = Tables.Lottery.First(p => p.ID == (int)lottery).IntervalType.Split(';');
            int Interval = int.Parse(tmp[1].Trim());
            string FirstEndTime = tmp[2].Trim();
            int Degree = int.Parse(tmp[3].Trim());

            for (int i = 0; i < date; i++)
            {
                string sDate = start.Date.ToShortDateString();

                DateTime IsuseStartTime;
                if (lottery == LotteryType.XJSSC)    //新疆时时彩,跨天型基诺彩票
                    IsuseStartTime = DateTime.Parse(sDate + " 2:0:0");
                else if (lottery == LotteryType.TC11X5)     //11选5 ，第一期为前一天的晚上 
                    IsuseStartTime = DateTime.Parse(sDate + " " + FirstEndTime.Trim()).AddSeconds((Degree - 1) * Interval).AddDays(-1);
                else
                    IsuseStartTime = DateTime.Parse(sDate + " 0:0:0");
                DateTime IsuseEndTime;
                if (lottery == LotteryType.CQSSC)
                    IsuseEndTime = DateTime.Parse(sDate + " 0:5:0");
                else if (lottery == LotteryType.HLJSSC)
                {
                    var HLJSSC_ReferenceTime = ConfigurationManager.AppSettings["HLJSSC_ReferenceTime"];
                    DateTime dt;
                    if (DateTime.TryParse(HLJSSC_ReferenceTime, out dt))
                    {
                        IsuseEndTime = DateTime.Parse(sDate + string.Format(" {0}:{1}:{2}", dt.Hour, dt.Minute, dt.Second));
                    }
                    else
                        IsuseEndTime = DateTime.Parse(sDate + " " + FirstEndTime);
                }
                else
                    IsuseEndTime = DateTime.Parse(sDate + " " + FirstEndTime);

                string Isuse = "";

                Isuse = start.Year.ToString() + start.Month.ToString().PadLeft(2, '0') + start.Day.ToString().PadLeft(2, '0') + "-01";

                if (lottery == LotteryType.CQSSC)
                    Isuse = start.Year.ToString() + start.Month.ToString().PadLeft(2, '0') + start.Day.ToString().PadLeft(2, '0') + "-001";


                rs.Add(new Issue() { LotteryID = (int)lottery, Number = Isuse, StartTime = IsuseStartTime, EndTime = IsuseEndTime });

                for (int j = 2; j <= Degree; j++)
                {
                    IsuseStartTime = IsuseEndTime;
                    if (lottery == LotteryType.CQSSC)
                    {
                        if (((IsuseStartTime >= DateTime.Parse(start.Date.ToShortDateString() + " 00:00:00") && IsuseStartTime < DateTime.Parse(start.Date.ToShortDateString() + " 02:00:00"))) || ((IsuseStartTime >= DateTime.Parse(start.Date.ToShortDateString() + " 22:00:00") && IsuseStartTime <= DateTime.Parse(start.Date.ToShortDateString() + " 23:59:59"))))
                        {
                            IsuseEndTime = IsuseEndTime.AddSeconds(Interval/2);
                            Isuse = start.Year.ToString() + start.Month.ToString().PadLeft(2, '0') + start.Day.ToString().PadLeft(2, '0') + "-" + j.ToString().PadLeft(3, '0');
                            if (j.ToString().PadLeft(2, '0') == "24")
                            {
                                IsuseStartTime = IsuseEndTime.AddSeconds(14400);
                                IsuseEndTime = IsuseStartTime.AddSeconds(14400);
                            }
                            if (j.ToString().PadLeft(3, '0') == "120")
                                IsuseEndTime = IsuseStartTime.AddSeconds(299);
                        }
                        else
                        {
                            IsuseEndTime = IsuseEndTime.AddSeconds(Interval);
                            Isuse = start.Year.ToString() + start.Month.ToString().PadLeft(2, '0') + start.Day.ToString().PadLeft(2, '0') + "-" + j.ToString().PadLeft(3, '0');
                        }
                    }
                    else
                    {
                        Isuse = start.Year.ToString() + start.Month.ToString().PadLeft(2, '0') + start.Day.ToString().PadLeft(2, '0') + "-" + j.ToString().PadLeft(2, '0');
                        if (lottery == LotteryType.JXSSC)
                        {   //2012-09-12更新，源于官方修改
                            if (j % 4 == 1)
                                IsuseEndTime = IsuseEndTime.AddSeconds(Interval+60);
                            else
                                IsuseEndTime = IsuseEndTime.AddSeconds(Interval);
                        }
                        else
                        {
                            IsuseEndTime = IsuseEndTime.AddSeconds(Interval);
                        }
                    }

                    rs.Add(new Issue() { LotteryID = (int)lottery, Number = Isuse, StartTime = IsuseStartTime, EndTime = IsuseEndTime });
                }

                start = start.AddDays(1);
            }

            return rs;
        }


        /// <summary>
        /// 生成期号(数字排列和福彩3D)
        /// </summary>
        /// <param name="lottery">彩种</param>
        /// <param name="start">开始日期，只要日期部份</param>
        /// <param name="date">生成多少天的期号</param>
        private IList<Issue> BuildIssueByDay(LotteryType lottery, DateTime start, int date)
        {
            IList<Issue> rs = new List<Issue>();

            if (lottery != LotteryType.SZPL && lottery != LotteryType.FC3D && lottery != LotteryType.HaoCai1)
                throw new System.ArgumentOutOfRangeException("lottery", lottery.ToString());

            string[] IntervalType = Tables.Lottery.First(p => p.ID == (int)lottery).IntervalType.Split(';');

            if (IntervalType.Length < 3)
                throw new System.ArgumentException("彩种" + lottery + "没有对应的IntervalType");

            double s = double.Parse(IntervalType[1]);
            double e = double.Parse(IntervalType[2]);

            DateTime starttime = start.Date.AddHours(s);
            DateTime endtime = start.Date.AddHours(e);
            string issuename = null;

            for (int i = 0; i < date; i++)
            {
                issuename = endtime.Year.ToString();
                issuename += endtime.DayOfYear.ToString().PadLeft(3, '0');

                rs.Add(new Issue() { Number = issuename, StartTime = starttime, EndTime = endtime, LotteryID = (int)lottery });

                starttime = starttime.AddDays(1);
                endtime = endtime.AddDays(1);
            }

            return rs;
        }
    }
}
